//登陆处理模块

var config=require('../config');
var User=require('../model/User');
var redis=require('../model/Redis');

//登陆页面
exports.login=function(req,res){
	var data={};
	//操作提醒
	var operate={"false":false,"msg":""};
	if(req.session.operate!=null) {
		operate=req.session.operate;
		delete req.session.operate;
	}
	data["operate"]=operate;
	data["loginCookie"]=req.signedCookies.ci_login||null;
	res.render('login',data);
}

//登入操作
exports.loginCheck=function(req,res){
	var email= req.body.email.trim();
	if(email==''){
		console.log('登陆失败');
		req.session.operate={"success":false,"msg":" 邮箱不能为空!"};
		return res.redirect('/login');
	}
	else{
		User.getUserInfoByMail(email,function(err,user){
			if(user){
				req.session.user=user;
				//记住用户名
				if(req.body.remember_me){
				    //Cookie
				    var cookie={"email":email,"remember_me":true};
				    res.cookie('ci_login', cookie, {maxAge: config.cookieTime, httpOnly: true,signed: true});
				}
				return res.redirect('/');
			}
			else{
				req.session.operate={"success":false,"msg":"账户错误!"};
				return res.redirect('/login');
			}
		});
	}
}

//登出操作
exports.logout=function(req,res){
	//清除session
	req.session.user=null;
	//删除cookie
	res.clearCookie('ci_login');
	res.redirect('/login');
}

